package mornd.test1;

import mornd.beans.Bean1;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.boot.web.servlet.server.ServletWebServerFactory;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.GenericApplicationContext;

import java.util.Collections;

/**
 * @author: mornd
 * @dateTime: 2023/5/10 - 15:57
 * SpringApplication 的构造器做了什么？
 */

//@SpringBootApplication
@Configuration
public class App {

     {if(false) SpringApplication.run(App.class);}

    public static void main(String[] args) throws Exception {
        SpringApplication spring = new SpringApplication(App.class);
        // SpringApplication 构造方法能干些什么？
        System.out.println("1、添加/获取 beanDefinition 源");
        // xml 方式添加 bean
        spring.setSources(Collections.singleton("classpath:bean02.xml"));

        System.out.println("2、推断应用类型");
        System.out.println(spring.getWebApplicationType());

        System.out.println("3、可以添加 applicationContext 初始化器（注册 bean）");
        spring.addInitializers(applicationContext -> {
            if(applicationContext instanceof GenericApplicationContext) {
                GenericApplicationContext context = (GenericApplicationContext) applicationContext;
                context.registerBean("bean3", Bean1.class);
            }
        });

        System.out.println("4、监听器与事件");
        spring.addListeners(event -> System.out.println(">>>>>>>>>事件触发：" + event.getClass()));

        System.out.println("主类推断");
        System.out.println(spring.getMainApplicationClass());

        ConfigurableApplicationContext context = spring.run(args);


        print(context);
        context.close();
    }

    private static void print(ConfigurableApplicationContext context) {
        String[] names = context.getBeanDefinitionNames();
        System.out.println("输出bean：" + names.length);
        for (String name : names) {
            BeanDefinition beanDefinition = context.getBeanFactory().getBeanDefinition(name);
            System.out.println("名称：" + name + " 来源：" + beanDefinition.getResourceDescription());
            System.out.println(beanDefinition + "\n");
        }
    }

    @Bean
    public ServletWebServerFactory servletWebServerFactory() {
        return new TomcatServletWebServerFactory(8080);
    }

    @Bean
    public Bean1 bean1() {
        return new Bean1();
    }
}
